/**
 * @author: YUPPIE
 * @date: 2025-04-18
 * @description: 用户管理模块
 * @version: 1.0
 *
 */

import {
  loginRequest,
  getCodeRequest,
  registerRequest,
  getUserInfoRequest,
} from "@/api/system/user";
import { ILogin } from "@/types/user";

export const useUserStore = defineStore("user", {
  state: () => ({
    count: 1,
    captchaImage: "",
    imgCode: "",
  }),
  getters: {},
  actions: {
    //登录
    async loginRequest(LoginFormData: ILogin) {
      try {
        let res = (await loginRequest(LoginFormData)) as any;
        if (res.code == 200) {
          ElMessage.success(res.message);
          localStorage.setItem("token", res.data.access_token);
          window.location.href = "/system";
        }
      } catch (error) {
        console.log(error);
      }
    },
    //注册
    async registerRequest(LoginFormData: ILogin) {
      try {
        let res = await registerRequest(LoginFormData);
        if (res.code == 200) {
          ElMessage.success("注册成功");
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取code
    async getCodeRequest() {
      try {
        let res = await getCodeRequest();

        this.imgCode = res.data.imgCode;
        this.captchaImage = res.data.img;
        // 将二进制数据转换为 Base64
        // const reader = new FileReader();
        // reader.readAsDataURL(res.data.img);
        // reader.onload = () => {
        //   console.log(reader);
        //   this.captchaImage = reader.result as string;
        // };
      } catch (error) {
        console.log(error);
      }
    },
    //登出
    logout() {},
    // 清除用户会话和缓存
    clearSessionAndCache() {},
    //获取用户信息
    async getUserInfoRequest() {
      try {
        let res = await getUserInfoRequest();
      } catch (error) {
        console.log(error);
      }
    },
  },
});
